package org.shj.book2.chapter01;

public class Main {

	public static void main(String[] args){
		Gate gate = new Gate();
		new UserThread(gate, "Alice", "Alaska").start();
		new UserThread(gate, "Bobby", "Brazil").start();
		new UserThread(gate, "Chris", "Canada").start();
	}
}

class Gate{
	private int counter = 0;
	private String name = "Nobody";
	private String address = "Nowhere";
	
	public void pass(String name, String address){
		this.counter++;
		this.name = name;
		/*try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/
		this.address = address;
		check();
	}
	
	public String toString(){
		return "No." + counter + ":" + name + ", " + address;
	}
	
	/**
	 * 从代码来看，name 和 address 是在同一个方法里被赋值的，它们的首字母应该是相等的，
	 * 但是从运行结果看，它们有可能不等。这是因为： 在多线程环境下，这种赋值方式是不安全的。
	 */
	public void check(){
		if(name.charAt(0) != address.charAt(0)){
			System.out.println("********** broken *****" + toString());
			//System.exit(-1);
		}
	}
}

class UserThread extends Thread{
	private final Gate gate;
	private final String myName;
	private final String myAddress;
	
	public UserThread(Gate gate, String myName, String myAddress){
		this.gate = gate;
		this.myAddress = myAddress;
		this.myName = myName;
	}
	
	public void run(){
		System.out.println(myName + " BEGIN...");
		while(true){
			gate.pass(myName, myAddress);
		}
	}
}
